// import { ElMessage } from 'element-plus'
import { createRouter, createWebHashHistory } from 'vue-router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
NProgress.configure({ showSpinner: false }) // NProgress Configuration

const router = createRouter({
  history: createWebHashHistory(),

  routes: [
    {
      path: '/',
      component: () => import('@/views/Layout'),
      children: [
        {
          path: '/',
          component: () => import('@/views/Home')
        },
        {
          path: '/system',
          component: () => import('@/views/System'),
          // 设置路由权限访问
          meta: { loginRequest: true },
          children: [
            {
              path: '/system',
              name: 'System',
              component: () => import('@/views/System/pages'),
              meta: { loginRequest: true }
            },
            {
              path: '/system/changeUserInfo',
              name: 'ChangeUserInfo',
              component: () => import('@/views/System/pages/changeUserInfo')
            },
            {
              path: '/system/orders',
              component: () => import('@/views/System/pages/orders.vue')
            }
          ]
        },
        // 分类
        {
          path: '/allcategory',
          component: () => import('@/views/AllCategory')
        },
        // 更多商品
        {
          path: '/search',
          component: () => import('@/views/Search')
        },
        // 商品详情
        {
          path: '/detail',
          name: 'Detail',
          component: () => import('@/views/Detail')
        }
      ]
    },
    {
      path: '/login',
      component: () => import('@/views/Login')
    }
  ]
})

router.beforeEach((to, from, next) => {
  NProgress.start()
  const hasToken = localStorage.getItem('token')
  if (to.meta.loginRequest) { // 如果路由meta中loginRequest为true，进行拦截
    if (hasToken) {
      next()
    } else {
      console.log(hasToken)
      next('/login')
    }
  } else {
    next()
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})

export default router
